package com.glela.email.service.impl;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import com.glela.email.service.EmailService;

import freemarker.template.Configuration;
import freemarker.template.TemplateException;

@Service("EmailService")
@Scope("singleton")
public class EmailServiceImpl implements EmailService {
	private static Logger logger = LoggerFactory.getLogger(EmailServiceImpl.class);
	
	/** 邮件模版根路径 */
	private static final String		MAIL_TEMPLATE_PATH	= "mail/";
	private static final String UTF_8 = "UTF-8";

	@Resource(name = "mailSender")
	private JavaMailSender mailSender;
	@Resource(name = "freemarker")
	private FreeMarkerConfigurer freemarker;
	@Value("${mail.from}")
	private String mail_from;
	private Configuration configuration;
	
	@Override
	public void sendEmail(String to, String subject, String content, boolean isHtml) throws MessagingException {
		MimeMessage msg = mailSender.createMimeMessage();
		MimeMessageHelper helper = new MimeMessageHelper(msg, true, UTF_8);
		if (StringUtils.isBlank(to)) {
			helper.setTo("gaoweiqi@pingdagroup.com");
		} else {
			helper.setTo(to);
		}
		helper.setSubject(subject);
		helper.setFrom(this.mail_from);
		helper.setText(content, isHtml);
		mailSender.send(msg);
	}

	@Override
	public void sendBatchEmail(String tos, String ccs, String subject, Map<String, String> content, Map<String, File> imgList, Map<String, File> fileList, String templateName) throws MessagingException, UnsupportedEncodingException {
		MimeMessage msg = mailSender.createMimeMessage();
		MimeMessageHelper helper = new MimeMessageHelper(msg, true, UTF_8);
		new InternetAddress();
		String contents = generateContent(content, MAIL_TEMPLATE_PATH + templateName);
		helper.setTo(InternetAddress.parse(tos));
		helper.setCc(InternetAddress.parse(ccs));
		helper.setFrom(this.mail_from);
		helper.setSubject(subject);
		helper.setText(contents, true);
		if (imgList != null) {
			for (String str : imgList.keySet()) {
				helper.addInline(str, imgList.get(str));
			}
		}
		if (fileList != null) {
			for (String str : fileList.keySet()) {
				helper.addAttachment(str, fileList.get(str));
			}
		}
		mailSender.send(msg);
	}
	
	public void setMailSender(JavaMailSender mailSender) {
		this.mailSender = mailSender;
	}
	
	public void setFreemarker(FreeMarkerConfigurer freemarker) {
		this.freemarker = freemarker;
	}
	
	public void setMail_from(String mail_from) {
		this.mail_from = mail_from;
	}
	
	/**
	 * 使用Freemarker生成html格式内容
	 * 
	 * @param replaceName  要替换的内容
	 * @param TemplateName  模板名
	 */
	protected String generateContent(Map<String, String> replaceName, String TemplateName) throws MessagingException {
		try {
			if (configuration == null) {
				configuration = freemarker.createConfiguration();
			}
			return FreeMarkerTemplateUtils.processTemplateIntoString(configuration.getTemplate(TemplateName), replaceName);
		} catch (IOException e) {
			logger.error("生成邮件内容失败, FreeMarker模板不存在", e);
			throw new MessagingException("FreeMarker模板不存在", e);
		} catch (TemplateException e) {
			logger.error("生成邮件内容失败, FreeMarker处理失败", e);
			throw new MessagingException("FreeMarker处理失败", e);
		}
	}
}
